﻿using System;
using System.Collections.Generic;
using Ur;

using Pixels.Logic;

namespace Pixels.Rendering
{
    public class Camera
    {

        public float zoom = 1.0f;
        public float zoomGoal = 1.0f;

        public float minZoom = 0.4f;
        public float maxZoom = 1.6f;

        public const float FACTOR = 128f;

        public crds2 project(crds3 worldCoords) {
            
            var transformedX = (worldCoords.x + worldCoords.y - ( this.coords.x + this.coords.y) ) * FACTOR * zoom;
            var transformedY = (worldCoords.y - worldCoords.x - (this.coords.y - this.coords.x) ) * FACTOR / 2 * zoom;
            
            return shalf + new crds2(transformedX, transformedY);
        }

        public crds2 unproject(crds2 screenCoords) {

            // many Bothan spies died to bring us this equation

            var sx = screenCoords.x; 
            var sy = screenCoords.y;
            var hx = shalf.x; 
            var hy = shalf.y;
            var F = FACTOR; 
            var z = zoom;
            var cx = coords.x; 
            var cy = coords.y;

            var alpha = (sx - hx) / (F*z);
            var beta = 2 * (sy - hy) / (F * z);

            var wX = (alpha -  beta + 2 * cx) / 2;
            var wY = alpha - wX + cx + cy;

            //var wX = (sx - hx - 2 * sy - 2 * hy) / (2 * F * z) + cx - cy;
            //var wY = (2 * sy - 2 * hy) / (F * z) + wX + cy + cx;
            return new crds2(wX, wY);

        }

        public crds2 coords;
        public crds2 target;

        void doStuff() {}

        crds2 shalf;

        public Camera() {
            shalf = new crds2(Sargon.Screen.w2, Sargon.Screen.h2);
            //zoom  = maxZoom + ((minZoom - maxZoom)/2);
            zoomGoal = zoom;
            target = coords = new crds2(50, 50);            
        }

    }

}
